package com.dut.bbs.activity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.R.integer;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.dut.bbs.R;
import com.dut.bbs.adapter.ArtlistAdapter;
import com.dut.bbs.data.ParseArticle;
import com.dut.bbs.entity.LoginEntity;
import com.dut.bbs.util.Dg;
import com.dut.bbs.util.NetWorkAvailable;
import com.dut.bbs.util.Settings;
import com.dut.bbs.util.StringUtils;
import com.dut.bbs.web.HtmlSource;

public class ArticleActivity extends BaseActivity {
	private ListView artlist;
	private List<Map<String,String>> ItemList;
	private Context context;
	private LinearLayout pop;
    private Button bt_next,bt_prev,bt_tag,bt_reply;
    private int currentPage; //当前页数
	private int maxPage;    //最大页数
	private String thread_url;
	private String board;
	private boolean isFav;
	private SharedPreferences settings;
	private int pos;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.thread);
		context = ArticleActivity.this;
		settings = PreferenceManager.getDefaultSharedPreferences(this);
		artlist = (ListView) findViewById(R.id.lv_threadlist);
		board = getIntent().getStringExtra("board").trim();
		thread_url = StringUtils.getBoradUrl(board);
		isFav = false;
		pos = 0;
		for(Map<String,String> map:Settings.favList){
			if(map.containsValue("版面|"+board+"|")){
				isFav = true;
				break;
			}
			pos++;
		}
		TextView tv_title = (TextView) findViewById(R.id.activitytitle);
		tv_title.setText("当前版面: "+board);
		artlist.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long arg3) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(ArticleActivity.this,
						ThreadActivity.class);
				intent.putExtra("url", ItemList.get(position).get("url"));
				intent.putExtra("title", ItemList.get(position).get("title"));
				startActivity(intent);

			}
		});
		initPopupWindow();
		setupViews();
		HtmlSourseGeter h = new HtmlSourseGeter(context);
		h.execute(thread_url);
	}
	class HtmlSourseGeter extends AsyncTask<String, integer, String>
    {

        private Context context;
        public HtmlSourseGeter(Context context)
        {
            this.context = context;
        }

        @Override
        protected String doInBackground(String... params)
        {
            String result = null;
            try
            {
                result = HtmlSource.getHtml_data(params[0]);
            } catch (Exception e)
            {
            }
            try{
            	currentPage = Integer.parseInt(result.split("页</a>\\|<a class=\"plant\">")[1].split("/")[0]);
            	maxPage = Integer.parseInt(result.split("页</a>\\|<a class=\"plant\">")[1].split("/")[1].split("<")[0]);
            }catch(Exception e){
            	currentPage=1;
            	maxPage=1;
            }
            return result;
        }

        @Override
        protected void onPreExecute()
        {
        	getProgressDialog().setMessage("抓取页面中...");
            getProgressDialog().show();
        }

        @Override
        protected void onPostExecute(String str)
        {

            String date = str;

            if (date == null)
            {
                Dg.showToast(context, "获取文章列表失败！");
                getProgressDialog().dismiss();
                return;
            }else if(date.contains("<div class=\"sp hl f\">您无权阅读此版面</div>")){
            	Dg.showToast(context, "您无权阅读此版面！");
                getProgressDialog().dismiss();
                return;
            }
            try{
    			ItemList = ParseArticle.getart(str);
    			ArtlistAdapter adapter = new ArtlistAdapter(context,ItemList);
                artlist.setAdapter(adapter);
            	getProgressDialog().dismiss();
            }catch(Exception e){
            	getProgressDialog().dismiss();
            	Dg.showToast(context, "抓取失败！");
            }                     
        }

    }
	private void initPopupWindow(){
    	pop = (LinearLayout) findViewById(R.id.ll_popmenu);
    	pop.setVisibility(View.VISIBLE);
    	TextView t = (TextView) pop.findViewById(R.id.tv_popreply);
    	t.setText("发帖");
    	bt_next = (Button) findViewById(R.id.btn_next);
    	bt_prev = (Button) findViewById(R.id.btn_prev);
    	bt_tag = (Button) findViewById(R.id.btn_tag);
    	TextView t1 = (TextView) pop.findViewById(R.id.tv_poptag);
    	bt_reply = (Button) findViewById(R.id.btn_reply);
    	if(!isFav){
    		bt_tag.setBackgroundResource(R.drawable.unfav);
    		t1.setText("收藏");
    	}else{
    		bt_tag.setBackgroundResource(R.drawable.fav);
    		t1.setText("取消收藏");
    	}
    }
	private void setupViews(){
    	bt_next.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				if(currentPage==maxPage)
					Dg.showToast(context, "已经是最后一页了");
				else{
					currentPage++;
					HtmlSourseGeter h1 = new HtmlSourseGeter(context);
					h1.execute(thread_url+"?p="+currentPage);
				}
			}
		});
    	bt_prev.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(currentPage==1)
					Dg.showToast(context, "已经是第一页了");
				else{
					currentPage--;
					HtmlSourseGeter h2 = new HtmlSourseGeter(context);
					h2.execute(thread_url+"?p="+currentPage);
				}
			}
		});
    	bt_reply.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(!LoginEntity.isLogin()){
					AlertDialog.Builder builder = new Builder(context);
					builder.setMessage("亲，你还没登录呢");
					builder.setTitle("提示");
					builder.setIcon(android.R.drawable.ic_dialog_alert);
					builder.setPositiveButton("去登录",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
									Intent intent = new Intent(context,LoginActivity.class);
									Bundle bundle = new Bundle();
									bundle.putString("fromItem", "1");
									intent.putExtras(bundle);
									context.startActivity(intent);
								}

							});
					builder.setNegativeButton(
							"算了吧",
							new android.content.DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
								}
							});
					builder.create().show();
				}else if(!NetWorkAvailable.goodNetIp()){
					Dg.showToast(context, "外网不能发帖哦，亲");
				}else{
					Intent in = new Intent(context,PostActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString("url", StringUtils.getPostURL(board));
					in.putExtras(bundle); 
					startActivity(in);
				}
			}
		});
    	bt_tag.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				SharedPreferences.Editor editor = settings.edit();
				if(isFav){
					String favStr = settings.getString("fav", "");
					if(Settings.favList.size()==1){
						favStr ="";
					}else{
						favStr = favStr.replaceAll(board+"\t"+thread_url+"\n", "");
					}
					editor.putString("fav", favStr);
					editor.commit();
					Settings.favList.remove(pos);
					isFav = false;
					initPopupWindow();
				}else{
					String favStr = settings.getString("fav", "");
					favStr += board+"\t"+thread_url+"\n";
					editor.putString("fav", favStr);
					editor.commit();
					Map<String,String> map = new HashMap<String,String>();
					map.put("title", "版面|"+board+"|");
					map.put("url", thread_url);
					Settings.favList.add(map);
					isFav = true;
					pos = Settings.favList.size()-1;
					initPopupWindow();
				}
			}
		});
    }
}
